//
//  XLNetworkTools.swift
//  LaowuquanS
//
//  Created by 王小林 on 26/9/18.
//  Copyright © 2018 王小林. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
/// 请求响应状态
///
/// - success: 响应成功
/// - unusual: 响应异常
/// - failure: 请求错误
enum XLRequestStatus: Int {
    case XLRequestStatusSuccess  = 0
    case XLRequestStatusLoginUserNotFound  = 404
    case XLRequestStatusLoginUserPasswordNotRight  = 501
    case XLRequestStatusLoginInOtherDevice        = 615     //账号在其他设备登录
    case XLRequestStatusAccessTokenExpired        = 10001   //token失效
    /*本地定义*/
    //网络失败
    case XLRequestStatusFailure
}

// 请求方法
enum MethodType {
    case get
    case post
}

/// 网络请求回调闭包 status:响应状态 result:JSON tipString:提示给用户的信息
typealias NetworkFinished = (_ status: XLRequestStatus, _ result: JSON?, _ tipString: String?) -> ()


class XLNetworkTools: NSObject {
    
    //开始请求
    class func requestData(_ type : MethodType, URLString : String, parameters : [String : Any]? = nil, finishedCallback :  @escaping NetworkFinished) {
        
        let URLStr = String(format: "%@%@", kAPIURL,URLString)
        
        let method = type == .get ? HTTPMethod.get : HTTPMethod.post
        
        Alamofire.request(URLStr, method: method, parameters: parameters).responseJSON { (response) in
            
            self.handle(response: response, finished: finishedCallback, needLoading: false)
            
            guard response.result.value != nil else {
                print(response.result.error!)
                return
            }
            
        }
    }
    /// 处理响应结果
    /// - Parameters: 
    ///   - response: 响应对象
    ///   - finished: 完成回调
    fileprivate class func handle(response: DataResponse<Any>, finished: @escaping NetworkFinished, needLoading: Bool) {
        
        if needLoading {
            //            HexaLoading.hide()
        }
        
        switch response.result {
        case .success(let value):
            let json = JSON(value)
            //打印结果
            #if DEBUG
            XLLog(json)
            #endif
            
            if json["state"].string == "1" {
                finished(.XLRequestStatusSuccess, json, json["msg"].string)
            } else {
                finished(.XLRequestStatusFailure, json, json["msg"].string)
            }
        case .failure(let error):
            XLLog(error)
            finished(.XLRequestStatusFailure, nil, error.localizedDescription)
        }
    }
    
    
    
}
